<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 4.2</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="4.1.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="4.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#4">Chapter 4. Statements</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><a name="localvar"><h2>4.2 &ndash; Local Variables and Blocks</h2></a>

<p>Besides global variables,
Lua supports local variables.
We create local variables with the <b>local</b> statement:
<pre>
    j = 10         -- global variable
    local i = 1    -- local variable
</pre>
Unlike global variables,
local variables have their <em>scope</em> limited to the block
where they are declared.
A block is the body of a control structure,
the body of a function,
or a chunk (the file or string with the code where the variable is declared).
<pre>
    x = 10
    local i = 1        -- local to the chunk
    
    while i&lt;=x do
      local x = i*2    -- local to the while body
      print(x)         --> 2, 4, 6, 8, ...
      i = i + 1
    end
    
    if i > 20 then
      local x          -- local to the "then" body
      x = 20
      print(x + 2)
    else
      print(x)         --> 10  (the global one)
    end
    
    print(x)           --> 10  (the global one)
</pre>
Beware that this example will not work as expected
if you enter it in interactive mode.
The second line, <code>local i = 1</code>,
is a complete chunk by itself.
As soon as you enter this line,
Lua runs it and starts a new chunk in the next line.
By then, the <b>local</b> declaration is already out of scope.
To run such examples in interactive mode,
you should enclose all the code in a <b>do</b> block.

<p>It is good programming style to use local variables whenever possible.
Local variables help you avoid cluttering the global
environment with unnecessary names.
Moreover, the access to local variables is
faster than to global ones.

<p>Lua handles local variable declarations as statements.
As such, you can write local declarations anywhere you can
write a statement.
The scope begins after the declaration and goes until the
end of the block.
The declaration may include an initial assignment,
which works the same way as
a conventional assignment:
Extra values are thrown away;
extra variables get <B>nil</B>.
As a specific case,
if a declaration has no initial assignment,
it initializes all its variables with <B>nil</B>.
<pre>
    local a, b = 1, 10
    if a&lt;b then
      print(a)   --> 1
      local a    -- `= nil' is implicit
      print(a)   --> nil
    end          -- ends the block started at `then'
    print(a,b)   -->  1   10
</pre>

<p>A common idiom in Lua is
<pre>
    local foo = foo
</pre>
This code creates a local variable, <code>foo</code>,
and initializes it with the value of the global variable <code>foo</code>.
That idiom is useful when the chunk needs to preserve
the original value of <code>foo</code> even if later some other function
changes the value of the global <code>foo</code>;
it also speeds up access to <code>foo</code>.

<p>Because many languages force you to declare all local variables
at the beginning of a block (or a procedure),
some people think it is a bad practice to use declarations
in the middle of a block.
Quite the opposite:
By declaring a variable only when you need it,
you seldom need to declare it without an initial value
(and therefore you seldom forget to initialize it).
Moreover, you shorten the scope of the variable,
which increases readability.

<p>We can delimit a block explicitly,
bracketing it with the keywords
<b>do</b>-<b>end</b>.
These <b>do</b> blocks can be useful when you need finer control
over the scope of one or more local variables:
<pre>
    do
      local a2 = 2*a
      local d = sqrt(b^2 - 4*a*c)
      x1 = (-b + d)/a2
      x2 = (-b - d)/a2
    end          -- scope of `a2' and `d' ends here
    print(x1, x2)
</pre>

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="4.3.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

